package com.niit.mobileDevide.devidemodelpatition;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.StringTokenizer;

public class UserBehaviorReducer extends Reducer<Text, Text, Text, Text> {

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        double appUsageSum = 0, screenOnSum = 0, batteryDrainSum = 0, appsInstalledSum = 0, dataUsageSum = 0;
        int count = 0;

        for (Text val : values) {
            StringTokenizer itr = new StringTokenizer(val.toString(), ",");
            while (itr.hasMoreTokens()) {
                appUsageSum += Double.parseDouble(itr.nextToken());
                screenOnSum += Double.parseDouble(itr.nextToken());
                batteryDrainSum += Double.parseDouble(itr.nextToken());
                appsInstalledSum += Double.parseDouble(itr.nextToken());
                dataUsageSum += Double.parseDouble(itr.nextToken());
                count++;
            }
        }

        if (count > 0) {
            // 计算平均值
            double avgAppUsage = appUsageSum / count;
            double avgScreenOn = screenOnSum / count;
            double avgBatteryDrain = batteryDrainSum / count;
            double avgAppsInstalled = appsInstalledSum / count;
            double avgDataUsage = dataUsageSum / count;

            // 构建输出字符串
            StringBuilder output = new StringBuilder();
            output.append("Average App Usage Time (min/day): ").append(avgAppUsage).append("\n");
            output.append("Average Screen On Time (hours/day): ").append(avgScreenOn).append("\n");
            output.append("Average Battery Drain (mAh/day): ").append(avgBatteryDrain).append("\n");
            output.append("Average Number of Apps Installed: ").append(avgAppsInstalled).append("\n");
            output.append("Average Data Usage (MB/day): ").append(avgDataUsage);

            // 输出结果
            context.write(key, new Text(output.toString()));
        } else {
            // 如果没有数据，输出提示信息
            context.write(key, new Text("No data available for this device model."));
        }
    }
}